<?php

declare(strict_types=1);

namespace App\Command;

use App\Constants\Redis\AdminCount;
use App\Constants\Redis\CooperativeCount;
use App\Utils\Mongo;
use App\Utils\Redis;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\DbConnection\Db;
use Psr\Container\ContainerInterface;

/**
 * 每天需要执行统计
 * @Crontab(name="Statistics", rule="*\/30 * * * *", callback="handle", memo="运营数据统计")
 * @Command
 */
class StatisticsCount extends HyperfCommand
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var Redis
     */
    protected $redis;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->redis = di(Redis::class);

        parent::__construct('StatisticsCount');
    }

    public function configure()
    {
        parent::configure();
        $this->setDescription('Operation data statistics');
    }

    public function handle()
    {
        /** 母公司后台汇总数据统计 */
        //昨日新增会员数
        $userCnt = Db::table('user')->whereRaw('TO_DAYS( NOW( ) ) - TO_DAYS(created_at) = 1')->count();
        $this->redis->set(AdminCount::YESTERDAY_ADD_USER,$userCnt);

        //昨日新增悬赏主
        $employer = Db::table('user')
            ->where('is_employer','=',1)
            ->whereRaw('TO_DAYS( NOW( ) ) - TO_DAYS(created_at) = 1')->count();
        $this->redis->set(AdminCount::YESTERDAY_ADD_EMPLOYER,$employer);

        //昨日新增合作商
        $cooper = Db::table('user')
            ->where('cooperative_id','>',0)
            ->whereRaw('TO_DAYS( NOW( ) ) - TO_DAYS(created_at) = 1')->count();
        $this->redis->set(AdminCount::YESTERDAY_ADD_COOPERATIVE,$cooper);

        //昨日成交佣金
        $gold = Db::table('user_gold_log')
            ->selectRaw('SUM(gold) as total')
            ->whereRaw('TO_DAYS( NOW( ) ) - TO_DAYS(created_at) = 1')->first();
        $this->redis->set(AdminCount::YESTERDAY_COMMISSION,intval($gold->total));

        //昨日悬赏主充值
        $recharge = Db::table('payment_log')
            ->selectRaw('SUM(money) as total')
            ->whereRaw('TO_DAYS( NOW( ) ) - TO_DAYS(created_at) = 1')->first();
        $this->redis->set(AdminCount::YESTERDAY_EMPLOYER_RECHARGE,intval($recharge->total));

        //昨日合作商收益
       $cooperPrice = Db::table('percentage')
            ->selectRaw('SUM(price) as total')
            ->whereRaw('TO_DAYS( NOW( ) ) - TO_DAYS(created_at) = 1')->first();
       $this->redis->set(AdminCount::YESTERDAY_COOPERATIVE_PROFIT,intval($cooperPrice->total));

        //总用户数
        $userTotal = Db::table('user')->count();
        $this->redis->set(AdminCount::USER_TOTAL,$userTotal);

        //总悬赏主数
        $employerTotal = Db::table('user')->where('is_employer','=',1)->count();
        $this->redis->set(AdminCount::EMPLOYER_TOTAL,$employerTotal);

        //总合作商数
        $cooperativeTotal = Db::table('user')->where('cooperative_id','>',0)->count();
        $this->redis->set(AdminCount::COOPERATIVE_TOTAL,$cooperativeTotal);


        /** 合作商后台汇总数据统计 */
        $coopers = Db::table('cooperative')->select('id')->get();
        foreach ($coopers as $val){
            //昨日新增用户数
            $coopersUser = Db::table('user')
                ->where('cooperative_id','=',$val->id)
                ->whereRaw('TO_DAYS( NOW( ) ) - TO_DAYS(created_at) = 1')->count();
            $key = sprintf(CooperativeCount::COOPER_ADD_USER,$val->id);
            $this->redis->set($key,$coopersUser);

            //昨日新增悬赏主
            $isEmployer = Db::table('user')
                ->where('is_employer','=',1)
                ->where('cooperative_id','=',$val->id)
                ->whereRaw('TO_DAYS( NOW( ) ) - TO_DAYS(created_at) = 1')->count();
            $key = sprintf(CooperativeCount::COOPER_ADD_EMPLOYER,$val->id);
            $this->redis->set($key,$isEmployer);

            //昨日成交佣金
            $userList = Db::table('user')->select('id')
                ->where('cooperative_id','=',$val->id)->get();
            $us = [];
            foreach ($userList as $item){
                array_push($us,$item->id);
            }
            $goldSum = Db::table('user_gold_log')
                ->selectRaw('SUM(gold) as total')
                ->whereIn('user_id',$us)
                ->whereRaw('TO_DAYS( NOW( ) ) - TO_DAYS(created_at) = 1')->first();
            $key = sprintf(CooperativeCount::COOPER_COMMISSION,$val->id);
            $this->redis->set($key,intval($goldSum->total));

            //昨日悬赏主充值
            $rechargeTotal = Db::table('payment_log')
                ->selectRaw('SUM(money) as total')
                ->where('cooperative_id','=',$val->id)
                ->whereRaw('TO_DAYS( NOW( ) ) - TO_DAYS(created_at) = 1')->first();
            $key = sprintf(CooperativeCount::COOPER_EMPLOYER_RECHARGE,$val->id);
            $this->redis->set($key,intval($rechargeTotal->total));

            //总用户数
            $coopUserTotal = Db::table('user')
                ->where('cooperative_id','=',$val->id)
                ->count();
            $key = sprintf(CooperativeCount::COOPER_USER_TOTAL,$val->id);
            $this->redis->set($key,$coopUserTotal);

            //总悬赏主数
            $coopEmployerTotal = Db::table('user')
                ->where('cooperative_id','=',$val->id)
                ->where('is_employer','=',1)->count();
            $key = sprintf(CooperativeCount::COOPER_EMPLOYER_TOTAL,$val->id);
            $this->redis->set($key,$coopEmployerTotal);

        }

        /** 柱状图部分 */

        //统计合作商新增用户数
        /** ------   全量数据处理    ------ **/
        //获取用户注册时间列表
        $dateList = Db::table('user')->select('created_at')->groupBy(['created_at'])->get();
        $coopers = Db::table('cooperative')->select('id')->get();
        $list = [];
        foreach ($coopers as $item) {
            foreach ($dateList as $val) {
              $list[$item->id][$val->created_at]['date'] = strtotime($val->created_at);
              $list[$item->id][$val->created_at]['cnt'] = Db::table('user')
                    ->where('cooperative_id','=',$item->id)
                    ->where('created_at','=',$val->created_at)
                    ->count();
            }
        }

        /** --------  增量数据处理  -------- **/

        /** -----------  保 存 ----------- **/
        //保存到mongo
        $mongo = di(Mongo::class);
        foreach ($list as $key=>$item){
           $dbKey = config('mongodb.default.db').'.barchart_'.$key;
           //先删除后增加
           $mongo->delete($dbKey);
           foreach ($item as $val){
               $mongo->insert($dbKey,$val);
           }
        }
    }

}
